package com.accesshollywood.grfxOrdering.panels;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.Timer;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.tree.TreePath;

import com.accesshollywood.SQL.GFXSQL;
import com.accesshollywood.grfxOrdering.GRFXOrdersMain;
import com.accesshollywood.grfxOrdering.OrderMainGUI;
import com.accesshollywood.grfxOrdering.SortedListModel;
import com.accesshollywood.grfxOrdering.basics.GrfxOrderListModel;
import com.accesshollywood.grfxOrdering.basics.GrfxOrders;
import com.accesshollywood.grfxOrdering.basics.Users;
import com.accesshollywood.indexables.GrfxOrder;
import com.accesshollywood.indexables.User;

public class OrderListPanel extends JPanel {
	private static final long			serialVersionUID	= -1357814291445012924L;
	JPopupMenu							rcPopup;
	private JList						orderList;
	private orderListSelectionListener	orderListListener	= new orderListSelectionListener();
	private DefaultListModel			orderListModel;
	public GrfxOrders.GrfxOrderGroup	grfxOrderRoot;

	JScrollPane							scrollPane_Right;
	public OrderTree2					orderTree;
	public GrfxOrderListModel			orderTreeModel;

	private SortedListModel				sortedOrderListModel;
	private JComboBox					comboView;
	JSplitPane							splitPane;
	public OrderMainGUI					parent;

	public ArrayList<Integer>			unfoldedOrderIDs	= new ArrayList<Integer>();
	public ArrayList<Integer>			orderNumbers		= new ArrayList<Integer>();

	private ViewFiltersMasterPanel		viewFilterPanel;

	/**
	 * Create the panel.
	 */
	public OrderListPanel(OrderMainGUI parent) {
		this.parent = parent;

		rcPopup = new JPopupMenu();

		orderListModel = new DefaultListModel();

		setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
		createGUI();
	}

	public GrfxOrder getSelectedOrder() {
		return orderTree.selectedOrder;
	}

	protected void createGrfxOrderTree() {
		if (orderTree == null) {
			orderTree = new OrderTree2(this);
		}
		orderTreeModel = new GrfxOrderListModel();
		orderTree.setModel(orderTreeModel);
	}

	public void createGUI() {
		splitPane = new JSplitPane();
		add(splitPane);

		viewFilterPanel = new ViewFiltersMasterPanel(this);
		viewFilterPanel.create();

		splitPane.setLeftComponent(viewFilterPanel);// scrollPane_Left);

		createGrfxOrderTree();

		scrollPane_Right = new JScrollPane(orderTree, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		splitPane.setRightComponent(scrollPane_Right);
		splitPane.setDividerLocation(200);
		splitPane.addMouseListener(new TreeRightClickListener());

		JPanel panel = new JPanel();
		panel.setAlignmentY(Component.TOP_ALIGNMENT);
		panel.setAlignmentX(Component.RIGHT_ALIGNMENT);
		add(panel);
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

		Component verticalGlue = Box.createVerticalGlue();
		panel.add(verticalGlue);

		CountdownTimer timer = new CountdownTimer();
//		refreshOrderModel();
	}

	public void refreshOrderModel() {
		orderNumbers = null;

		String whereConditions = "(idOrder>0) ";// +
												// getWhereConditions((ViewFilterTreeNode)
												// viewFilterTreeModel.getRoot());
		whereConditions += viewFilterPanel.getWhereConditions();

		Integer[] rawOrderNumbers = GFXSQL.getInt(viewFilterPanel.searchColumn, "idOrder", whereConditions + " ORDER BY dueDate, block, idOrder");
		if (rawOrderNumbers != null) {
			orderNumbers = new ArrayList<Integer>(Arrays.asList(rawOrderNumbers));
			orderTree.refresh(orderNumbers);
		}

	}

	public void refreshConnections() {
		GFXSQL.refreshConnections();
	}

	public void refreshOrderGUI(boolean fromSQL) {
		// fromSQL isn't doing anything right now...
		for (int i = 0; i < orderTree.getComponentCount(); i++) {
			Component c = orderTree.getComponent(i);
			if (c instanceof SingleOrderPanel) {
				OrderMainGUI.allFoldables.remove(c);
				// Trace.info("preHEIGHT: " + c.getBounds().height);
			}
		}

		orderTree.removeAll();

		orderTree.parent.remove(orderTree);
		orderTree = null;
		createGrfxOrderTree();
		scrollPane_Right = new JScrollPane(orderTree, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		int divider = splitPane.getDividerLocation();
		splitPane.setRightComponent(scrollPane_Right);
		splitPane.setDividerLocation(divider);

		refreshOrderModel();

		//GRFXOrdersMain.gui.setVisible(true);

//		OrderMainGUI.setFoldablesMaxHeight();

		for (int i = 0; i < orderTree.getComponentCount(); i++) {
			Component c = orderTree.getComponent(i);
			if (c instanceof SingleOrderPanel) {
				// Trace.info("preHEIGHT: " + c.getBounds().height);
			}
		}
	}

	public void refreshOrderGUI(String fieldName, int idOrder, boolean fromSQL) {
		SingleOrderPanel currPanel = orderTree.displayedOrderPanels.get(idOrder);
		OrderHeaderPanel orderHeaderPanel = (OrderHeaderPanel) currPanel.headerPanel;
		OrderDetailsPanel orderDetailsPanel = (OrderDetailsPanel) currPanel.foldUpPanel;

		if (fromSQL) {
			currPanel.model.refreshfromSQL(fieldName);
		}

		if (fieldName.equals("showName") ||
				fieldName.equals("summary") ||
				fieldName.equals("block") ||
				fieldName.equals("graphicType") ||
				fieldName.equals("orderedBy") ||
				fieldName.equals("researcher") ||
				fieldName.equals("artist") ||
				fieldName.equals("producer") ||
				fieldName.equals("footage") ||
				fieldName.equals("legal")) {
			orderHeaderPanel.refresh();
		} else if (fieldName.equals("apprResearch") ||
				fieldName.equals("apprPhotoEdit") ||
				fieldName.equals("apprFootage") ||
				fieldName.equals("apprLegal")) {
			(orderDetailsPanel).approvalPanel.refresh();
		} else if (fieldName.equals("complete") ||
				fieldName.equals("complete") ||
				fieldName.equals("closed") ||
				fieldName.equals("archived")) {
			(orderDetailsPanel).approvalPanel.refresh();
			orderHeaderPanel.refresh();
		} else if (fieldName.equals("items") ||
				fieldName.equals("needsResearch") ||
				fieldName.equals("needsPhotoEdit") ||
				fieldName.equals("needsFootage") ||
				fieldName.equals("needsLegal") ||
				fieldName.equals("dueDate")) {
			refreshOrderGUI(fromSQL);
		}
	}

	public void refreshOrderTreeModel() {
		Integer[] orderNumbers = null;

		String whereConditions = "(idOrder>0) ";// +
		orderNumbers = GFXSQL.getInt("gfxOrder", "idOrder", whereConditions);

		GrfxOrderListModel model = new GrfxOrderListModel();

		if (orderNumbers != null) {
			// Trace.info("Getting orders");
			GrfxOrders currOrders = new GrfxOrders(orderNumbers);
			// orderTree.setModel(new DefaultTreeModel(currOrders.getRoot()));
		}
	}

	public void remakeTree(GrfxOrders currOrders) {

	}

	public void populateRightClickPopup(GrfxOrder currOrder, boolean isTree) {
		User currUser = Users.currentUser;
		rcPopup.removeAll();
		if (isTree) {
			JMenuItem itemOrderNumber = new JMenuItem("Order: " + currOrder.getId() + ":  " + currOrder.getSummary());
			itemOrderNumber.setEnabled(false);
			rcPopup.add(itemOrderNumber);

			rcPopup.addSeparator();

			if (currUser.isAdmin() || currUser.isPhotoEdit()) {
				JMenuItem itemEditOrder = new JMenuItem("Edit Order");
				rcPopup.add(itemEditOrder);
			}
			if (currUser.isAdmin() || currUser.isArtist()) {
				JMenuItem itemGrabOrder = new JMenuItem("Grab Order");
				rcPopup.add(itemGrabOrder);
				JMenuItem itemCompleteOrder = new JMenuItem("Mark Complete");
				rcPopup.add(itemCompleteOrder);
			}
			if (currOrder.isNeedsResearch() && (currUser.isAdmin() || currUser.isResearch())) {
				JMenuItem itemApprResearch = new JMenuItem("Approve Research");
				rcPopup.add(itemApprResearch);
			}
			if (currOrder.isNeedsPhotoEdit() && (currUser.isAdmin() || currUser.isPhotoEdit())) {
				JMenuItem itemApprPhotoEdit = new JMenuItem("Approve PhotoEdit");
				rcPopup.add(itemApprPhotoEdit);
			}
			if (currOrder.isNeedsFootage() && (currUser.isAdmin() || currUser.isFootage())) {
				JMenuItem itemApprFootage = new JMenuItem("Approve Footage");
				rcPopup.add(itemApprFootage);
			}
			if (currOrder.isNeedsLegal() && (currUser.isAdmin() || currUser.isLegal())) {
				JMenuItem itemApprLegal = new JMenuItem("Approve Legal");
				rcPopup.add(itemApprLegal);
			}
		} else {
			if (currUser.isAdmin() || currUser.isOrderer()) {
				JMenuItem itemNewOrder = new JMenuItem("New Order");
				rcPopup.add(itemNewOrder);
			}
		}
	}

	/*
	 * public String getWhereConditions(ViewFilterTreeNode currNode) {
	 * String where = (currNode.whereCondition.equals("")) ? "" : " || " +
	 * currNode.whereCondition;
	 * // for(int i = 0; i < currNode.getChildCount(); i++){
	 * // if(checkTreeManager.){
	 * TreePath checkedPaths[] =
	 * checkTreeManager.getSelectionModel().getSelectionPaths();
	 * if (checkedPaths != null) {
	 * for (int i = 0; i < checkedPaths.length; i++) {
	 * // where +=
	 * // getWhereConditions((ViewFilterTreeNode)currNode.getChildAt(i));
	 * where = (currNode.whereCondition.equals("")) ? "" : " || " +
	 * currNode.whereCondition;
	 * }
	 * }
	 * // }
	 * // }
	 * return where;
	 * }
	 */

	class orderListSelectionListener implements ListSelectionListener {
		public void valueChanged(ListSelectionEvent arg0) {
			// GrfxOrderModel currOrder = (GrfxOrderModel)
			// orderList.getSelectedValue();
			// parent.addEditPanel.updateOrderDisplay(currOrder);
		}
	}

	public class TreeRightClickListener extends MouseAdapter {
		private void myPopupEvent(MouseEvent e) {
			int x = e.getX();
			int y = e.getY();

			JTree tree = (JTree) e.getSource();
			TreePath path = tree.getPathForLocation(x, y);
			tree.setSelectionPath(path);
			if (path == null) {
				populateRightClickPopup(null, false);// not the tree
			} else {
				Object obj = path.getLastPathComponent();
				if (obj instanceof GrfxOrder) {
					populateRightClickPopup((GrfxOrder) obj, true);// is the
																	// tree
				}
			}
			rcPopup.show(tree, x, y);
		}

		public void mousePressed(MouseEvent e) {
			if (e.isPopupTrigger())
				myPopupEvent(e);
		}

		public void mouseReleased(MouseEvent e) {
			if (e.isPopupTrigger())
				myPopupEvent(e);
		}
	}

	public class CountdownTimer implements ActionListener {
		Timer	timer;

		public CountdownTimer() {
			timer = new Timer(1000, this);
			timer.setInitialDelay(0);
			timer.setCoalesce(true);
			timer.start();
		}

		@Override
		public void actionPerformed(ActionEvent arg0) {
			if (orderTree != null) {
				orderTree.repaint();
			}
		}
	}
}
